/*
 * User: rant
 * Date: Jul 19, 2007
 *
 *
 */
package laMalinche.rete.rule;


import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class BasicRuleMap implements RuleMap {
    private static final Logger log = LogManager.getLogger(BasicRuleMap.class);
    private final Map<BusinessRuleType, Map<String, ProductionRule>> ruleMap = new HashMap<BusinessRuleType, Map<String, ProductionRule>>();

    public BasicRuleMap() {
        initializeRuleMap();
    }

    public Map<BusinessRuleType, Map<String, ProductionRule>> getReadOnlyRuleMap() {
        return new HashMap<BusinessRuleType, Map<String, ProductionRule>>(ruleMap);
    }

    private void initializeRuleMap() {
        for (BusinessRuleType type : BusinessRuleType.values()) {
            Map<String, ProductionRule> rulesMap = new HashMap<String, ProductionRule>();
            ruleMap.put(type, rulesMap);
        }
    }

    public void registerRule(ProductionRule rule) {
        String key;
        final BusinessRuleType type = rule.getProductionRuleType();
        final Map<String, ProductionRule> map = ruleMap.get(type);
        if (type.isDerivationField()) {
            final FieldRule derivationRule = ((FieldRule) rule);
            key = derivationRule.getDerivedFieldOgnl();
        } else {
            key = rule.getAction().getName();
        }
        if (map.containsKey(key)) {
            log.error("rule " + key + "was declared more then nonce");
        } else {
            map.put(key, rule);
        }
    }

}